package com.thinkgem.jeesite.modules.spider.pipeline;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.thinkgem.jeesite.modules.cms.entity.Article;
import com.thinkgem.jeesite.modules.cms.entity.ArticleData;
import com.thinkgem.jeesite.modules.cms.entity.Category;
import com.thinkgem.jeesite.modules.cms.service.ArticleDataService;
import com.thinkgem.jeesite.modules.cms.service.ArticleService;
import com.thinkgem.jeesite.modules.cms.service.CategoryService;
import com.thinkgem.jeesite.modules.spider.common.SpiderConstants;
import com.thinkgem.jeesite.modules.spider.entity.SpiderLog;
import com.thinkgem.jeesite.modules.spider.service.SpiderLogService;

import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

@Component
public class CnblogsPipeline implements Pipeline {
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private ArticleService articleService;
	@Autowired
	private ArticleDataService articleDataService;
	@Autowired
	private SpiderLogService logService;

	private Category category;

	@Override
	public void process(ResultItems resultItems, Task task) {
		Article article = resultItems.get("article");
		ArticleData articleData = resultItems.get("articleData");
		String categoryId = "312a736691624c67853f8ed5e968f190";
		if (category == null) {
			category = categoryService.get(categoryId);
		}
		article.setCategory(category);
		article.setArticleData(articleData);
		articleData.setArticle(article);
		if (article != null && articleData != null) {
			try {
				articleService.save(article);
				articleDataService.save(articleData);
			} catch (Exception e) {
				logService.save(new SpiderLog("ArticleData", SpiderConstants.LOG_LEVEL_ERROR, e.getLocalizedMessage()));
				logger.error("insert article error !");
			}
			logger.debug("articleTitle==>" + article.getTitle());
		}

	}

}
